package cn.cvs.controller;

import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysUserService;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import sun.security.pkcs11.wrapper.Constants;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户模块
 */
@Controller
@RequestMapping(value = "/user")
public class SysUserController {
    private Logger logger = Logger.getLogger(SysUserController.class);

    @Resource
    private SysUserService sysUserService;

    //跳转到登录页面
    @RequestMapping(value = "/toLogin")
    public String login(){
        logger.debug("跳转到登录页面");
        return "login";
    }

    //登录
    @PostMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, @RequestParam String account, @RequestParam String password){
        logger.debug("登录方法");
        //调用 service 方法，进行用户匹配
        SysUser sysUser = sysUserService.login(account,password);
        if (null != sysUser) {
//            session.setAttribute(Constants.USER_SESSION,sysUser);
            //登录成功，重定向到/user/toMain接口
            return "redirect:/user/toMain";
        }else{
            request.setAttribute("error","用户名或密码不正确");
            //用户不存在，登录失败，跳转到登录页面
            return "login";
        }
    }

    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session){
//        if (session.getAttribute(Constants.USER_SESSION) == null) {
//            return "redirect:/user/toLogin";
//        }
        return "frame";
    }

    private ArrayList<SysUser> sysUserList = new ArrayList<SysUser>();
    //用于返回查询到的用户数据
    private ArrayList<SysUser> queryUserList = new ArrayList<SysUser>();

    public SysUserController() {
        try {
            sysUserList.add(new SysUser(5,"zhaojing","赵静","5555555",1,"13054784445","上海市宝山区",1,1,new Date(),1,new Date()));
            sysUserList.add(new SysUser(4,"wanglin","王林","4444444",1,"18965652364","北京市学院路",1,1,new Date(),1,new Date()));
            sysUserList.add(new SysUser(1,"test001","测试用户 003","1111111",1,"13566669998","北京市朝阳区",1,1,new Date(),1,new Date()));
            sysUserList.add(new SysUser(2,"zhaoyan","赵燕","2222222",1,"18678786545","北京市海淀区",1,1,new Date(),1,new Date()));
            sysUserList.add(new SysUser(3,"test003","测试用户 003","1111111",1,"13121334531","北京市海淀区",1,1,new Date(),1,new Date()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询所有用户
    @GetMapping("/list")
    public String list(Model model){
        logger.info("当查询条件为空时，查询用户信息");
        queryUserList.clear();
        queryUserList.addAll(sysUserList);
        model.addAttribute("queryUserList",queryUserList);
        return "sysUser/sysUserList";
    }

    //根据查询条件部分用户
    @PostMapping("/list")
    public String list(@RequestParam(value = "realName",required = false)String realName,Model model){
        logger.info("查询条件：【realName】 = "+realName+"，查询用户信息");
        queryUserList.clear();
        if (realName != null && !realName.equals("")){
            for (SysUser sysUser : sysUserList) {
                if (sysUser.getRealName().indexOf(realName) != -1){
                    queryUserList.add(sysUser);
                }
            }
        }else{
            queryUserList.addAll(sysUserList);
        }
        model.addAttribute("queryUserList",queryUserList);
        return "sysUser/sysUserList";
    }

    /**
     * 查询用户详情
     */
    @RequestMapping(value = "/view",method = RequestMethod.GET)
    public String view() {
        logger.info("查询用户详情");
        return null;
    }
    /**
     * 保存用户信息
     */
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String save() {
        logger.info("保存用户信息");
        return null;
    }

    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest request){
        request.setAttribute("e",e);
        return "error";
    }

    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account,@RequestParam String password){
        SysUser user = sysUserService.login(account,password);
        if (null == user){
            throw new RuntimeException("用户名或者密码不正确！");
        }
        return "redirect:/user/toMain";
    }

    //跳转到添加用户页面
    @GetMapping("/toAdd")
    public String toAdd(){
        return "sysUser/add";
    }

//    @PostMapping("/add")
//    public String add(SysUser sysUser,HttpSession session){
//        sysUser.setCreatedUserId(((SysUser)session.getAttribute(
//                Constants.USER_SESSION
//        )).getId());
//        if(sysUserService.add(sysUser)){
//            return "redirect:/user/list";
//        }
//        return "sysUser/add";
//    }

    public String view(@PathVariable String id,Model model){
        logger.debug("根据 id 查询用户详情"+id);
        SysUser userById = sysUserService.getUserById(id);
        model.addAttribute(userById);
        return "sysUser/view";
    }

    public String toUpdate(@RequestParam String uid,Model model){
        logger.debug("跳转到修改用户信息页面");
        SysUser userById = sysUserService.getUserById(uid);
        model.addAttribute(userById);
        return "sysUser/update";
    }

    @GetMapping("/add")
    public String toAdd(@ModelAttribute("sysUser") SysUser sysUser){
        return "sysUser/add";
    }

//    @PostMapping("/add")
//    public String add(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session){
//        if (bindingResult.hasErrors()){
//            logger.debug("添加用户验证失败");
//            return "sysUser/add";
//        }
//
//        sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
//
//        if (sysUserService.add(sysUser)){
//            return "redirect:/user/list";
//        }
//        return "sysUser/add";
//    }

    //修改用户信息
//    @PostMapping("/update")
//    public String update(SysUser sysUser,HttpSession session){
//        logger.debug("修改用户信息");
//        sysUser.setUpdatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
//        if(sysUserService.update(sysUser)){
//            return "redirect:/user/list";
//        }
//        return "sysUser/update";
//    }

//    @GetMapping("/list")
//    public String getUserList(Model model,String queryRealName,Integer queryRoleId,@RequestParam(defaultValue = "1") Integer pageIndex){
//        List<SysUser> userList = null;
//        try {
//            //设置页面容量
//            int pageSize = Constants.pageSize;
//            //总数量（表）
//            int totalCount = sysUserService.getUserCount(queryRealName,queryRoleId);
//            //总页数
//            PageSupport pages = new PageSupport();
//            pages.setCurrentPageNo(pageIndex);
//            pages.setPageSize(pageSize);
//            pages.setTotalCount(totalCount);
//            int totalPageCount = pages.getTotalPageCount();
//            //控制首页和尾页
//            if (pageIndex > totalPageCount) {
//                pageIndex = totalPageCount;
//                throw new RuntimeException("页码不正确");
//            }
//            userList = sysUserService.getUserList(queryRealName,queryRoleId,pageIndex,pageSize);
//            model.addAttribute("userList",userList);
//            List<SysRole> roleList = null;
//            roleList = sysUserService.getRoleList();
//            model.addAttribute("roleList",roleList);
//            model.addAttribute("queryRealName",queryRealName);
//            model.addAttribute("queryRoleId",queryRoleId);
//            model.addAttribute("totalPageCount",totalPageCount);
//            model.addAttribute("totalCount",totalCount);
//            model.addAttribute("currentPageNo",pageIndex);
//        }catch (Exception e){
//            e.printStackTrace();
//            logger.error("用户列表接口访问失败");
//            return "redirect:/user/toSysError";
//        }
//        return "sysUser/list";
//    }

    @RequestMapping(value = "/totSysError")
    public String sysError(){
        return "sysError";
    }
}
